<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>文件上传</title>
</head>
<body>
  <!-- 表单默认提交的数据格式是 application/x-www-form-urlencoded -->
  <!-- 如果要通过表单上传文件，必须设置成multipart/form-data格式  -->
  <form method="post" action="http://localhost:8888/api/upload" enctype="multipart/form-data">
    <input type="file" name="avatar" id="avatar">
    <button id="btn">提交</button>
  </form>
  <img src="" id="img">
  <script type="text/javascript">
    // 基于原生Ajax上传文件
    var btn = document.getElementById('btn')
    btn.onclick = function (e) {
      e.preventDefault()
      // 上传文件
      var xhr = new XMLHttpRequest()
      xhr.open('post', 'http://localhost:8888/api/upload')
      
      var input = document.getElementById('avatar')
      var fd = new FormData()
      fd.append('avatar', input.files[0])
      xhr.send(fd)
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            var ret = xhr.responseText
            var obj = JSON.parse(ret)
            // console.log(ret)
            var img = document.getElementById('img')
            img.src = obj.data
          }
        }
      }
    }
  </script>
</body>
</html>